package com.carrentalplatform.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Web资源控制器
 * 提供静态资源访问
 */
@Controller
public class WebConfig {

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;

    /**
     * 图片资源访问接口
     */
    @GetMapping("/uploads/vehicle/{date}/{filename:.+}")
    @ResponseBody
    public void getVehicleImage(@PathVariable String date, 
                                @PathVariable String filename,
                                HttpServletResponse response) throws IOException {
        
        // 构建文件路径
        Path imagePath = Paths.get(uploadPath, "vehicle", date, filename);
        File file = imagePath.toFile();
        
        // 检查文件是否存在
        if (!file.exists() || !file.isFile()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }
        
        // 获取文件类型
        String contentType = Files.probeContentType(imagePath);
        if (contentType == null) {
            // 根据文件扩展名判断
            if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg")) {
                contentType = "image/jpeg";
            } else if (filename.toLowerCase().endsWith(".png")) {
                contentType = "image/png";
            } else if (filename.toLowerCase().endsWith(".gif")) {
                contentType = "image/gif";
            } else {
                contentType = "application/octet-stream";
            }
        }
        
        // 设置响应头
        response.setContentType(contentType);
        response.setContentLength((int) file.length());
        
        // 将文件内容写入响应
        try (FileInputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "读取文件失败");
        }
    }
    
    /**
     * 占位图片资源访问接口
     */
    @GetMapping("/assets/no-image.png")
    @ResponseBody
    public void getPlaceholderImage(HttpServletResponse response) throws IOException {
        // 在classpath下创建一个资源文件夹，将占位图片放在那里
        // 可以使用resources/static/assets/no-image.png
        // 或者直接返回一个默认图片
        
        // 设置响应头
        response.setContentType("image/png");
        
        // 使用内置的占位图
        String basePath = System.getProperty("user.dir");
        Path placeholderPath = Paths.get(basePath, "src", "main", "resources", "static", "assets", "no-image.png");
        File placeholderFile = placeholderPath.toFile();
        
        // 如果文件不存在，使用备用路径
        if (!placeholderFile.exists() || !placeholderFile.isFile()) {
            // 尝试其他可能的路径
            placeholderPath = Paths.get(basePath, "src", "main", "resources", "public", "assets", "no-image.png");
            placeholderFile = placeholderPath.toFile();
            
            // 如果还是不存在，返回错误
            if (!placeholderFile.exists() || !placeholderFile.isFile()) {
                // 如果文件不存在，返回一个简单的图片
                // 这里我们可以创建一个1x1的透明像素
                byte[] pixel = new byte[] {
                    (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
                    0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08,
                    0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, (byte) 0xC4, (byte) 0x89, 0x00, 0x00, 0x00,
                    0x0B, 0x49, 0x44, 0x41, 0x54, 0x08, 0x1D, 0x63, (byte) 0xF8, 0x0F, 0x00, 0x01,
                    0x01, 0x01, 0x00, (byte) 0xBB, (byte) 0xAC, 0x0F, (byte) 0xCD, 0x00, 0x00, 0x00,
                    0x00, 0x49, 0x45, 0x4E, 0x44, (byte) 0xAE, 0x42, 0x60, (byte) 0x82
                };
                
                response.setContentLength(pixel.length);
                response.getOutputStream().write(pixel);
                response.getOutputStream().flush();
                return;
            }
        }
        
        // 设置内容长度
        response.setContentLength((int) placeholderFile.length());
        
        // 将文件内容写入响应
        try (FileInputStream in = new FileInputStream(placeholderFile);
             OutputStream out = response.getOutputStream()) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "读取占位图失败");
        }
    }
} 